/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ep.m005.ui.controllers;

import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import ep.libs.implementations.AbstractModule;
import ep.persistence.controllers.T001UserJpaController;
import ep.persistence.controllers.T006PrescriptionJpaController;
import ep.persistence.controllers.T008DosageJpaController;
import ep.persistence.controllers.T009MedicineJpaController;
import ep.persistence.controllers.T012DiagnosisJpaController;
import ep.persistence.controllers.T013FrequencyJpaController;
import ep.persistence.entities.T001User;
import ep.persistence.entities.T002Doctor;
import ep.persistence.entities.T005Patient;
import ep.persistence.entities.T005T007;
import ep.persistence.entities.T006Prescription;
import ep.persistence.entities.T008Dosage;
import ep.persistence.entities.T009Medicine;
import ep.persistence.entities.T010Substance;
import ep.persistence.entities.T012Diagnosis;
import ep.persistence.entities.T013Frequency;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Query;

/**
 *
 * @author Spyros
 */
public class M005Controller {

    private AbstractModule module;
    private T006Prescription prescription;
    private T005Patient patient;
    private T002Doctor doctor;

    public M005Controller(Object patientObject, Integer prescriptionId, AbstractModule module) {
        this.patient = (T005Patient) patientObject;
        this.module = module;
        findPrescription(prescriptionId);
        findDoctor();
    }

    public BeanItem<T005Patient> getPatientDataSource() {
        BeanItem<T005Patient> beanItem = new BeanItem<T005Patient>(patient);
        return beanItem;
    }

    public BeanItem<T002Doctor> getDoctorDataSource() {
        BeanItem<T002Doctor> beanItem = new BeanItem<T002Doctor>(doctor);
        return beanItem;
    }

    public BeanItem<T006Prescription> getPrescDataSource() {
        BeanItem<T006Prescription> beanItem;
        if (prescription == null) {
            prescription = new T006Prescription();
        }
        beanItem = new BeanItem<T006Prescription>(prescription);
        return beanItem;
    }

    public BeanItemContainer<T008Dosage> getDosageDataSource() {
        BeanItemContainer<T008Dosage> beanItemContainer;
        if (prescription == null) {
            beanItemContainer = new BeanItemContainer<T008Dosage>(T008Dosage.class);
        } else {
            beanItemContainer = new BeanItemContainer<T008Dosage>(T008Dosage.class, prescription.getT008DosageCollection());
        }
        return beanItemContainer;
    }

    public BeanItemContainer<T012Diagnosis> getDiagnosisDataSource() {
        T012DiagnosisJpaController jpaController = new T012DiagnosisJpaController();
        return new BeanItemContainer<T012Diagnosis>(T012Diagnosis.class, jpaController.findT012DiagnosisEntities());
    }

    public BeanItemContainer<T013Frequency> getFrequencyDataSource() {
        T013FrequencyJpaController jpaController = new T013FrequencyJpaController();
        Collection<T013Frequency> tfs = jpaController.findT013FrequencyEntities();
        BeanItemContainer<T013Frequency> beanItemContainer = new BeanItemContainer<T013Frequency>(T013Frequency.class, tfs);
        return beanItemContainer;
    }

    public BeanItemContainer<T009Medicine> getMedicineDataSource() {
        T009MedicineJpaController jpaController = new T009MedicineJpaController();
        Collection<T009Medicine> tms = jpaController.findT009MedicineEntities();
        BeanItemContainer<T009Medicine> beanItemContainer = new BeanItemContainer<T009Medicine>(T009Medicine.class, tms);
        return beanItemContainer;
    }

    public String checkSubstances(Collection dosages) {
        final Collection<T010Substance> patientSubstances = new ArrayList<T010Substance>();
        for (Iterator<T005T007> it = patient.getT005T007Collection().iterator(); it.hasNext();) {
            T005T007 t005t007 = it.next();
            patientSubstances.addAll(t005t007.getT007Illness().getT010Substances());
        }
        for (Iterator it = dosages.iterator(); it.hasNext();) {
            T008Dosage t008Dosage = (T008Dosage) it.next();
            Collection medicSubs = t008Dosage.getT009Medicine().getT010Substances();
            for (Iterator it1 = medicSubs.iterator(); it1.hasNext();) {
                T010Substance substance = (T010Substance) it1.next();
                if (patientSubstances.contains(substance)) {
                    return substance.getName();
                }
            }
        }
        return null;
    }

    public boolean save(BeanItem prescBeanItem, Collection dosages) {
        return save(prescBeanItem, dosages, false);
    }

    public boolean save(BeanItem prescBeanItem, Collection dosages, boolean repeat) {
        try {
            //save prescription
            T006PrescriptionJpaController prescriptionJpaController = new T006PrescriptionJpaController();
            prescription = (T006Prescription) prescBeanItem.getBean();
            prescription.setT002Doctor(doctor);
            prescription.setT005Patient(patient);
            prescription.setPrescDate(new Date());
            if (prescription.getId() == null) {
                prescriptionJpaController.create(prescription);
            } else {
                if (repeat) {
                    prescription.setT008DosageCollection(new ArrayList<T008Dosage>());
                    prescriptionJpaController.create(prescription);
                } else {
                    prescriptionJpaController.edit(prescription);
                }
            }
            //save dosage
            T008DosageJpaController dosageJpaController = new T008DosageJpaController();
            for (Iterator it = dosages.iterator(); it.hasNext();) {
                T008Dosage dosage = (T008Dosage) it.next();
                if (repeat) {
                    dosage.setPrescribed(false);
                }
                dosage.setT006Prescription(prescription);
                if (dosage.getId() == null) {
                    dosageJpaController.create(dosage);
                } else {
                    if (repeat) {
                        dosageJpaController.create(dosage);
                    } else {
                        dosageJpaController.edit(dosage);
                    }
                }
            }
//            prescription.setT008DosageCollection(dosages);
//            prescriptionJpaController.edit(prescription);

            return true;
        } catch (Exception e) {
            Logger.getLogger(M005Controller.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }

    }

    private void findDoctor() {
        String username = (String) ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().getAttribute("username");
        T001UserJpaController jpaController = new T001UserJpaController();
        Query query = jpaController.getEntityManager().createNamedQuery("T001User.findByUsername", T001User.class);
        query.setParameter("username", username);
        if (prescription != null && prescription.getT002Doctor() != null) {
            doctor = prescription.getT002Doctor();
        } else {
            T001User user = (T001User) query.getResultList().iterator().next();
            if (!user.getT002DoctorCollection().isEmpty()) {
                doctor = user.getT002DoctorCollection().iterator().next();
            }
        }
    }

    private void findPrescription(Integer id) {
        T006PrescriptionJpaController jpaController = new T006PrescriptionJpaController();
        prescription = jpaController.findT006Prescription(id);
    }
}
